<template>
  <PageLayout full :page-style="pageStyle">
    <template #header>
      <HeaderLayout
        show-back
        :title="$t('Appliance.Settings.FirmwareUpgrade.Title')"
        :header-style="headerStyle"
      ></HeaderLayout>
    </template>

    <!-- 待升级 / 升级中 -->
    <view class="update-view" v-if="initData">
      <SettingGroup>
        <SettingRow padding="24rpx 32rpx">
          <view class="menu-item">
            <view class="icon">
              <image mode="aspectFit" :src="'/pages/appliance/static/Upgrade.png'" />
            </view>
            <!-- 普通固件升级 -->
            <block v-if="!isMR120">
              <view v-if="otaHelper && otaHelper.upgradeDetected.value" class="content">
                <view class="title">{{ $t('Appliance.Settings.FirmwareUpgrade.NewVersionDetected.Title') }}</view>
                <view class="desc">{{
                  otaHelper.remoteUpgradeSupported && !otaHelper.remoteUpgradeSupported.value
                    ? $t('Appliance.Settings.FirmwareUpgrade.RemoteUpgradeNotSupported.Text')
                    : $t('Appliance.Settings.FirmwareUpgrade.NewVersionDetected.Content')
                }}</view>
              </view>
              <view v-else class="content">
                <view class="title">{{ $t('Appliance.Settings.FirmwareUpgrade.CurrentIsLatestVersion.Title') }}</view>
              </view>
            </block>

            <!-- MR120 -->
            <block v-if="isMR120">
              <view v-if="mr120UpgradeDetected" class="content">
                <view class="title">{{ $t('Appliance.Settings.FirmwareUpgrade.NewVersionDetected.Title') }}</view>
                <view class="desc">{{ $t('Appliance.Settings.FirmwareUpgrade.NewVersionDetected.Content') }}</view>
              </view>
              <view v-else class="content">
                <view class="title">{{ $t('Appliance.Settings.FirmwareUpgrade.CurrentIsLatestVersion.Title') }}</view>
              </view>
            </block>
          </view>
        </SettingRow>
      </SettingGroup>

      <!-- 更新按钮 -->
      <view
        v-if="
          otaHelper &&
          otaHelper.upgradeDetected.value &&
          (!otaHelper.remoteUpgradeSupported || otaHelper.remoteUpgradeSupported.value)
        "
        class="update-button"
      >
        <SettingGroup>
          <SettingRow :disabled="otaHelper?.upgradingModalVisible.value" @click="otaHelper && otaHelper.allowUpgrade()">
            <view class="update-button-inner">
              <text>{{
                otaHelper?.upgradingModalVisible.value
                  ? $t('Appliance.Settings.FirmwareUpgrade.Upgrading.Button.Text')
                  : $t('Appliance.Settings.FirmwareUpgrade.UpgradeNow.Button.Text')
              }}</text>
            </view>
          </SettingRow>
        </SettingGroup>
      </view>

      <!-- MR120更新按钮 -->
      <view v-if="isMR120 && mr120UpgradeDetected" class="update-button">
        <SettingGroup>
          <SettingRow @click="updateMR120Ota">
            <view class="update-button-inner">
              <text>{{
                isRuningUpdate
                  ? $t('Appliance.Settings.FirmwareUpgrade.Upgrading.Button.Text')
                  : $t('Appliance.Settings.FirmwareUpgrade.UpgradeNow.Button.Text')
              }}</text>
            </view>
          </SettingRow>
        </SettingGroup>
      </view>
    </view>

    <!-- MR120 OTA升级弹框 -->
    <block v-if="isMR120">
      <OtaUpgrade
        from="applianceSet"
        ref="mr120OtaUpgradeRef"
        :show="isMR120"
        :ha-id="haId"
        :mcu-status="mcuStatus"
        @update="isUpgrade = $event"
        @change-run="isRuningUpdate = $event"
        @change-fail="isUpdateFail = $event"
        @change-sucess="isUpdateSucess = $event"
      />
    </block>
    <!-- 普通固件升级弹框 -->
    <block v-else-if="otaHelper">
      <FirmwareModals :helper="otaHelper" />
    </block>
  </PageLayout>
</template>

<script setup lang="ts">
import PageLayout from '@/layout/page/page.vue'
import HeaderLayout from '@/layout/page/header.vue'
import OtaUpgrade from '../../TT/otaUpgrade/otaUpgrade.vue'

import type { OTAHelper } from './helpers/types'
import SettingGroup from '@/common/setting/SettingGroup.vue'
import SettingRow from '@/common/setting/SettingRow.vue'
import { TT_STATUS_MCUSTATUS } from '../../TT/SmartAssistantTool'
import { getPageQuery, showLoading } from '@/utils/mpHelper'
import { useWebsocketListener } from '@/utils/socket/WebSocketHandlerImp'
import type { WS } from '@/utils/socket/types'
import { WebsocketManager } from '@/utils/socket/WebsocketManager'
import { TrackType, trackEvent } from '@/dataReport/tracks'
import { getOtaUpgradeList } from '@/api/tt'
import FirmwareModals from './firmwareModals.vue'

const props = defineProps<{
  haId: string
  otaHelper: OTAHelper | null
}>()

const pageStyle = {
  backgroundColor: '#f4f4f6',
}
const headerStyle = {
  backgroundColor: '#fff',
}

const haId = computed(() => props.haId)
const initData = ref(false)
const mcuStatus = ref(0)

/**
 * TT MR120
 */
const isMR120 = computed(() => props.haId.indexOf('MR120') !== -1)
const isUpgrade = ref(false)
const isUpdateSucess = ref(false)
const isUpdateFail = ref(false)
const isRuningUpdate = ref(false)
const mr120UpgradeDetected = computed(
  () => (isUpgrade.value || isRuningUpdate.value || isUpdateFail.value) && !isUpdateSucess.value
)
const mr120OtaUpgradeRef = ref<InstanceType<typeof OtaUpgrade> | null>(null)
async function loadData() {
  if (isMR120.value) return initMR120Ota()

  if (props.otaHelper) {
    try {
      await showLoading(() =>
        Promise.all([props.otaHelper?.checkUpgrade(), props.otaHelper?.checkRemoteUpgradeSupported()])
      )
    } catch (e) {
      console.error(e)
    }
  }
  initData.value = true
}

async function initMR120Ota() {
  const query = getPageQuery()
  mcuStatus.value = Number(query.mcuStatus)
  listenMR120Messages()
  await judgeMR120AllOtaVersion()
}
loadData()

/**
 * 立即升级
 */
async function updateMR120Ota() {
  trackEvent('firmware_update', {}, TrackType.ApplianceDetail, 'Appliance.Settings.FirmwareUpgrade.Update')
  mr120OtaUpgradeRef.value?.confirmUpdate('applianceSet')
}

/**
 * 监听
 */
function listenMR120Messages() {
  useWebsocketListener(WebsocketManager.instance.oemWebsocket, (msg: WS.Message) => {
    if (msg.haId !== haId.value || !Array.isArray(msg.items)) return
    msg.items.forEach((item) => {
      if (item.key === TT_STATUS_MCUSTATUS) {
        mcuStatus.value = Number(item.value)
      }
    })
  })
}
/**
 * 判断是否需要升级
 */
async function judgeMR120AllOtaVersion() {
  await showLoading(async () => {
    const res = await getOtaUpgradeList(haId.value)
    if (res.code === 0 && res.data) {
      isUpgrade.value = res.data.some((item) => item.upgrade)
      initData.value = true
    } else {
      uni.showToast({
        title: '加载接口失败',
        icon: 'error',
      })
    }
  })
}
</script>

<style scoped lang="less">
.update-view {
  padding: 16rpx 0;
}

.menu-item {
  display: flex;
  overflow: hidden;
  .icon {
    flex-shrink: 0;
    width: 88rpx;
    height: 88rpx;
    margin-right: 16rpx;
    image {
      width: 100%;
      height: 100%;
    }
  }
  .content {
    flex: 1;
    display: flex;
    flex-flow: column nowrap;
    justify-content: center;
    align-items: flex-start;
  }
  .title {
    font-weight: 500;
    font-size: 32rpx;
    line-height: 44rpx;
    color: var(--dark-color);
  }
  .desc {
    margin-top: 8rpx;
    padding-bottom: 8rpx;
    font-weight: 400;
    font-size: 28rpx;
    line-height: 40rpx;
    color: #575f6b;
  }
}
.update-button {
  margin-top: 16rpx;
  color: var(--primary-color);
}
.update-button-inner {
  text-align: center;
}
</style>
